//
//  NVFilterController.m
//  Dianping
//
//  Created by ZhouHui on 12-4-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "NVFilterController.h"
#import "NVPopoverView.h"
#import <QuartzCore/QuartzCore.h>

#define NVFilterControllerSeparateLineViewTag               59900
#define NVFilterButtonPopoverArrowImageViewTag             40000
typedef enum {
    NVFilterControllerFilter1OnOffMask      = 1 << FilterType1,
    NVFilterControllerFilter2OnOffMask      = 1 << FilterType2,
    NVFilterControllerFilter3OnOffMask      = 1 << FilterType3
} NVFilterControllerFilterOnOffMask;

@implementation NVPickerObject
@synthesize leftObject, rightArray;
+ (id)pickerObjectWithLeftObject:(id)left withRightArray:(NSArray *)right {
	return [[[self alloc] initWithLeftObject:left withRightArray:right] autorelease];
}

- (id)initWithLeftObject:(id)left withRightArray:(NSArray *)right {
	self = [super init];
	if (self) {
		self.leftObject = left;
		self.rightArray = right;
	}
	return self;
}

- (void)dealloc {
	self.leftObject = nil;
	self.rightArray = nil;
    [super dealloc];
}
@end

@interface NVFilterController()

- (void)updateFilterButtonAppearance;

@end

@implementation NVFilterController
{
    UIButton *filterButton1;
	UIButton *filterButton2;
	UIButton *filterButton3;
}
@synthesize filterCount = _filterCount;
@dynamic filterText1;
@dynamic filterText2;
@dynamic filterText3;
@synthesize filterStyle;
@synthesize delegate;
@synthesize disable = _disable;
@synthesize filterBtnOnOffState=_filterBtnOnOffState;
@synthesize filterViewSection1=filterButton1;
@synthesize filterViewSection2=filterButton2;
@synthesize filterViewSection3=filterButton3;
@synthesize filter1NeedsDarkTabImage=_filter1NeedsDarkTabImage;
@synthesize filter2NeedsDarkTabImage=_filter2NeedsDarkTabImage;
@synthesize filter3NeedsDarkTabImage=_filter3NeedsDarkTabImage;
#define kDefaultFilterCount	3
- (void)initialWithFilterCount:(int)filterCnt {
    self.filterStyle = NVFilterOnOffSwitchStyle;
	self.backgroundColor = [UIColor clearColor];
	self.filterCount = filterCnt;
    self.filter1NeedsDarkTabImage = NO;
    self.filter2NeedsDarkTabImage = NO;
    self.filter3NeedsDarkTabImage = NO;
//	UIImageView *imgSeperate = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Seperate_Line_Dropdown"]];
//	imgSeperate.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
//	imgSeperate.frame = CGRectMake(0, CGRectGetHeight(self.frame)-1, CGRectGetWidth(self.frame), 1);
//    imgSeperate.layer.borderColor = [UIColor redColor].CGColor;
//    imgSeperate.layer.borderWidth = 1;
//    imgSeperate.tag = NVFilterControllerSeparateLineViewTag;
//	[self addSubview:imgSeperate];
}

- (id)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame withFilterCount:kDefaultFilterCount];
}

- (id)initWithFrame:(CGRect)frame withFilterCount:(int)filterCnt {
	self = [super initWithFrame:frame];
	if (self) {
		[self initialWithFilterCount:filterCnt];
	}
	return self;
}

- (void)awakeFromNib {
	[self initialWithFilterCount:kDefaultFilterCount];
}

- (void)setDisable:(BOOL)disable {
	_disable = disable;
	filterButton1.enabled = !disable;
	filterButton2.enabled = !disable;
	filterButton3.enabled = !disable;
}

- (void)setEnable:(BOOL)enable buttonIndex:(int)index{
    if(index == 1){
        filterButton1.enabled = enable;
    }
    if(index == 2){
        filterButton2.enabled = enable;
    }
    if(index == 3){
        filterButton3.enabled = enable;
    }
}

- (UIButton *)createFilterButton {
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button addTarget:self action:@selector(filterButtonAction:) forControlEvents:UIControlEventTouchUpInside];
	[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
	[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button setBackgroundImage:[UIImage imageNamed:@"FilterTab_Normal"]
                      forState:UIControlStateNormal];
    
	button.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
	button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
	button.titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
	button.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
	button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
	
	return button;
}

- (void)createTabSelectedArrowView
{
    UIImage *image = [UIImage imageNamed:@"Tab_Selected_Arrow"];
    selectedTabImageView =[[UIImageView alloc] initWithImage:image];
    selectedTabImageView.tag = NVFilterButtonPopoverArrowImageViewTag;
    selectedTabImageView.center = CGPointZero;
    selectedTabImageView.hidden = YES;
    [self addSubview:selectedTabImageView];
    [self bringSubviewToFront:selectedTabImageView];
}

-(void)updateFilterButtonAppearance 
{
    if(self.filterStyle != NVFilterNormalStyle) {
        

        if(_filterBtnOnOffState & NVFilterControllerFilter1OnOffMask) {
            
            selectedTabImageView.center = CGPointMake(filterButton1.center.x ,CGRectGetHeight(self.bounds) - selectedTabImageView.image.size.height*0.5);
            selectedTabImageView.hidden = NO;
            
            if(self.filter1NeedsDarkTabImage)
                selectedTabImageView.image = [UIImage imageNamed:@"Tab_Selected_Arrow_Dark"];
            else 
                selectedTabImageView.image = [UIImage imageNamed:@"Tab_Selected_Arrow"];
            
            [self bringSubviewToFront:selectedTabImageView];

			dropImage1.layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);

        }
        else {
			dropImage1.layer.transform = CATransform3DIdentity;
        }
        if(_filterBtnOnOffState & NVFilterControllerFilter2OnOffMask) {
            
            selectedTabImageView.center = CGPointMake(filterButton2.center.x ,CGRectGetHeight(self.bounds) - selectedTabImageView.image.size.height*0.5);
            selectedTabImageView.hidden = NO;
            
            if(self.filter2NeedsDarkTabImage)
                selectedTabImageView.image = [UIImage imageNamed:@"Tab_Selected_Arrow_Dark"];
            else 
                selectedTabImageView.image = [UIImage imageNamed:@"Tab_Selected_Arrow"];            [self bringSubviewToFront:selectedTabImageView];

//            selectedTabImageView.layer.borderColor = [UIColor greenColor].CGColor;
//            selectedTabImageView.layer.borderWidth = 1;
			dropImage2.layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
        }
        else {
			dropImage2.layer.transform = CATransform3DIdentity;
        }
        if(_filterBtnOnOffState & NVFilterControllerFilter3OnOffMask) {
            
            selectedTabImageView.center = CGPointMake(filterButton3.center.x ,CGRectGetHeight(self.bounds) - selectedTabImageView.image.size.height*0.5);
            selectedTabImageView.hidden = NO;
            if(self.filter3NeedsDarkTabImage)
                selectedTabImageView.image = [UIImage imageNamed:@"Tab_Selected_Arrow_Dark"];
            else 
                selectedTabImageView.image = [UIImage imageNamed:@"Tab_Selected_Arrow"];            [self bringSubviewToFront:selectedTabImageView];
            
            [self bringSubviewToFront:selectedTabImageView];

//            selectedTabImageView.layer.borderColor = [UIColor greenColor].CGColor;
//            selectedTabImageView.layer.borderWidth = 1;
            
			dropImage3.layer.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
        }
        else {
			dropImage3.layer.transform = CATransform3DIdentity;
        }
        
        if((_filterBtnOnOffState &(NVFilterControllerFilter1OnOffMask|NVFilterControllerFilter2OnOffMask|NVFilterControllerFilter3OnOffMask)) == 0) {
            selectedTabImageView.hidden = YES;
        }
    }
}

- (void)setFilterCount:(NSUInteger)filterCount {
	if (filterCount>3) {
		filterCount = 3;
	}
	if (filterCount == _filterCount || filterCount<1) {
		return;
	}
	_filterCount = filterCount;
	// 首先删除所有界面元素
	NSArray *subViews = self.subviews;
	for (UIView *subView in subViews) {
		[subView removeFromSuperview];
	}
	
	// 添加界面元素
#define kGapWidth	1
    [self createTabSelectedArrowView];
    
	float width = self.frame.size.width;
	float eachButtonWidth = width/(float)_filterCount;
	float buttonHeight = self.frame.size.height;
	float x = 0;
	
	filterButton1 = [self createFilterButton];
	[self addSubview:filterButton1];
	filterButton1.frame = CGRectMake(x, 0, eachButtonWidth, buttonHeight);
	dropImage1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ArrowDown.png"]];
	dropImage1.frame = CGRectMake((x+eachButtonWidth-25), (buttonHeight-13)/2, 13, 13);
	[self addSubview:dropImage1];
    
    
	if (_filterCount<2) {
		return;
	}
	
	x+=eachButtonWidth;
	filterButton2 = [self createFilterButton];
	[self addSubview:filterButton2];
	filterButton2.frame = CGRectMake(x, 0, eachButtonWidth, buttonHeight);
	dropImage2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ArrowDown.png"]];
	dropImage2.frame = CGRectMake((x+eachButtonWidth-25), (buttonHeight-13)/2, 13, 13);
	[self addSubview:dropImage2];
    
    UIImageView *gapView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(x, 0, kGapWidth, buttonHeight-1)] autorelease];
	gapView1.image = [UIImage imageNamed:@"FilterGap.png"];
	[self addSubview:gapView1];
	[self bringSubviewToFront:gapView1];

	if (_filterCount<3) {
		return;
	}
	
	x+=eachButtonWidth;
	UIImageView *gapView2 = [[[UIImageView alloc] initWithFrame:CGRectMake(x, 0, kGapWidth, buttonHeight-1)] autorelease];
	gapView2.image = [UIImage imageNamed:@"FilterGap.png"];
	[self addSubview:gapView2];
	filterButton3 = [self createFilterButton];
	[self addSubview:filterButton3];
	filterButton3.frame = CGRectMake(x, 0, eachButtonWidth, buttonHeight);
	dropImage3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ArrowDown.png"]];
	dropImage3.frame = CGRectMake((x+eachButtonWidth-25), (buttonHeight-13)/2, 13, 13);
	[self addSubview:dropImage3];
    
	[self bringSubviewToFront:gapView1];
	[self bringSubviewToFront:gapView2];
}

- (NSString *)filterText1 {
	return [filterButton1 titleForState:UIControlStateNormal];
}

- (void)setFilterText1:(NSString *)filterText {
	[filterButton1 setTitle:filterText forState:UIControlStateNormal];
}

- (void)setFilterStyle:(NVFilterStyle)theFilterStyle 
{
    filterStyle = theFilterStyle;

    _filterBtnOnOffState = 0;

    [filterButton1 setBackgroundImage:[UIImage imageNamed:@"FilterTab_Normal"]
                             forState:UIControlStateNormal];
    [filterButton2 setBackgroundImage:[UIImage imageNamed:@"FilterTab_Normal"]
                             forState:UIControlStateNormal];
    [filterButton3 setBackgroundImage:[UIImage imageNamed:@"FilterTab_Normal"]
                             forState:UIControlStateNormal];
    
}

- (void)setFilterBtnOnOffState:(NSInteger)theState
{
    if(_filterBtnOnOffState != theState) {
        _filterBtnOnOffState = theState;
        [self updateFilterButtonAppearance];
    }
}

- (NSString *)filterText2 {
	return [filterButton2 titleForState:UIControlStateNormal];
}

- (void)setFilterText2:(NSString *)filterText {
	[filterButton2 setTitle:filterText forState:UIControlStateNormal];
}

- (NSString *)filterText3 {
	return [filterButton3 titleForState:UIControlStateNormal];
}

- (void)setFilterText3:(NSString *)filterText {
	[filterButton3 setTitle:filterText forState:UIControlStateNormal];
}

- (BOOL)filter1NeedsOn
{
    return (self.filterBtnOnOffState & NVFilterControllerFilter1OnOffMask);
}

- (BOOL)filter2NeedsOn
{
    return (self.filterBtnOnOffState & NVFilterControllerFilter2OnOffMask);        
}

- (BOOL)filter3NeedsOn
{
    return (self.filterBtnOnOffState & NVFilterControllerFilter3OnOffMask);    
}

- (void)resetFilterBtnsStates
{
    [self setFilterBtnOnOffState:0];
}

- (void)filterButtonAction:(id)sender {
    
	if([NVPopoverView popoverIsShowed]) {
        [NVPopoverView sharedPopoverView].delegate = nil;
        [NVPopoverView dismissPopoverViewAnimated:NO];
    }
	
    FilterType theFilterType;
    
	if(sender == filterButton1) {
        theFilterType = FilterType1;
	} else if(sender == filterButton2) {
        theFilterType = FilterType2;
	} else if(sender == filterButton3) {
        theFilterType = FilterType3;
	}
    
    if(self.filterStyle == NVFilterOnOffStyle) {
        
        NSInteger theMask = 1<<(theFilterType);
        //keep all other btns states, change this btn states(normal or selected)
        _filterBtnOnOffState = _filterBtnOnOffState^theMask;
    }
    else if(self.filterStyle == NVFilterSwitchStyle) {
        //all other btns off(normal) , make this btn on(selected) 
        _filterBtnOnOffState = 1<<(theFilterType);
    }
    else if(self.filterStyle == NVFilterNormalStyle) {
        //all btns off(normal)
        _filterBtnOnOffState = 0;
    }
    else if(self.filterStyle == NVFilterOnOffSwitchStyle) {
        NSInteger theMask = 1<<(theFilterType);
        //all other btns off(normal),keep this btn states(normal or selected)
        _filterBtnOnOffState = _filterBtnOnOffState&theMask;
        //change this btns states(selected or normal)
        _filterBtnOnOffState = _filterBtnOnOffState^theMask;
    }
    
    [self updateFilterButtonAppearance];

    if (delegate && [delegate respondsToSelector:@selector(filterController:touchedFilter:)]) {
        [delegate filterController:self touchedFilter:theFilterType];
    }
}

- (void)showPickerWithFilterType:(FilterType)ft selectedRow1:(NSInteger)row1 selectedRow2:(NSInteger)row2 {

}   

- (void)didAddSubview:(UIView *)subview
{
    UIView *view = [self viewWithTag:NVFilterControllerSeparateLineViewTag];
    [self bringSubviewToFront:view];
}

@end
